package com.jswitch.server.process.requset;

import com.jswitch.common.enums.TransactionStateEnum;
import com.jswitch.server.cache.SipDialogManageCache;
import com.jswitch.server.cache.TransactionManageCache;
import com.jswitch.server.msg.SipMessageEvent;
import com.jswitch.server.process.AbstractSipMessageProcess;
import com.jswitch.server.transaction.ServerSipTransaction;
import com.jswitch.server.transaction.SipTransactionUser;
import com.jswitch.sip.DialogState;
import com.jswitch.sip.SipDialog;
import com.jswitch.sip.SipRequest;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import java.util.Objects;

@Slf4j
@Component("ACK")
public class AckSipMessageProcess extends AbstractSipMessageProcess {



    @Override
    public void handleRequest(SipMessageEvent event) {
        SipRequest sipRequest = (SipRequest) event.getMessage();
        SipDialog sipDialog = SipDialogManageCache.getSipDialog(sipRequest.getDialogId(true));
        if (Objects.nonNull(sipDialog)) {
            ServerSipTransaction serverTransaction = TransactionManageCache.getServerTransaction(sipDialog.getTransactionId());
            TransactionStateEnum transactionState = serverTransaction.getState();

            // 根据事务状态处理 ACK 消息
            if (transactionState == TransactionStateEnum.COMPLETED) {
                // 在 COMPLETED 状态，ACK 通常用于确认 INVITE 的最终响应
                sipDialog.setState(DialogState.CONFIRMED);
                serverTransaction.processRequest(sipRequest); // 通知事务处理 ACK
            } else if (transactionState == TransactionStateEnum.CONFIRMED) {
                // 在 CONFIRMED 状态下处理重复的 ACK（可能是重传）
                log.info("ACK retransmission detected. Dialog state is already CONFIRMED.");
            } else if (transactionState == TransactionStateEnum.TERMINATED) {
                // 如果事务已经终止，忽略 ACK
                log.info("ACK received for terminated transaction. Ignoring.");
            } else {
                // 其他状态下可能不会接收到 ACK
                log.warn("Unexpected ACK received in transaction state: " + transactionState);
            }
        } else {
            log.warn("No dialog found for ACK request: " + sipRequest);
        }
    }
}
